package com.ys.utils.mobao;


import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.util.*;

/**
 * Created by roger on 2019/2/25.
 */
public class CommonUtil {

    /**
     * 排序拼接需要加签或者验签的字符串，key=value&
     * @param data
     * @return
     * @throws Exception
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static String coverMap2String(Map data) throws Exception{
        List<String> list = new ArrayList<String>();
        list.addAll(data.keySet());
        Collections.sort(list);

        StringBuffer sf = new StringBuffer();
        for (String key : list) {
            Object value = data.get(key);

            if (StringUtils.isEmpty(key)||"signMsg".equals(key.trim())||null==value|| StringUtils.isEmpty(value.toString())) {
                continue;
            }
            sf.append(new StringBuilder().append(key).append("=").append(value).append("&").toString());
        }
        if(sf.length()>0){
            return sf.substring(0, sf.length() - 1);
        }
        return sf.toString();
    }

    public static Map<String, String> obj2Map(Object obj) {

        Map<String, String> map = new HashMap<String, String>();
        // System.out.println(obj.getClass());
        // 获取f对象对应类中的所有属性域
        Field[] fields = obj.getClass().getDeclaredFields();
        for (int i = 0, len = fields.length; i < len; i++) {
            String varName = fields[i].getName();
            try {
                // 获取原来的访问控制权限
                boolean accessFlag = fields[i].isAccessible();
                // 修改访问控制权限
                fields[i].setAccessible(true);
                // 获取在对象f中属性fields[i]对应的对象中的变量
                Object o = fields[i].get(obj);
                if (o != null)
                    map.put(varName, o.toString());
                // System.out.println("传入的对象中包含一个如下的变量：" + varName + " = " + o);
                // 恢复访问控制权限
                fields[i].setAccessible(accessFlag);
            } catch (IllegalArgumentException ex) {
                ex.printStackTrace();
            } catch (IllegalAccessException ex) {
                ex.printStackTrace();
            }
        }
        if(map.containsKey("signMsg")){
            map.remove("signMsg");
        }
        return map;
    }

}
